<template>
    <view class="lin-coupon-page">
        <!-- 1. 顶部导航栏 -->
        <view class="custom-nav">
            <view class="nav-item" v-for="(item, index) in navList" :key="index"
                  :class="{ 'active': activeNav === index }" @click="loadCoupons(index)">
                {{ item }}
            </view>
        </view>

        <!-- 2. 可领取优惠券列表 -->
        <view class="coupon-list">
            <!-- 单个优惠券卡片 -->
            <view class="coupon-card" v-for="(item, index) in couponList" :key="index">
                <!-- 快过期角标 -->
                <view class="expired-tag" v-if="item.isExpired">快过期</view>
                <!-- 内容容器：左金额 + 右信息 -->
                <view class="coupon-content">
                    <!-- 左侧金额区域 -->
                    <view class="amount-wrap">
                        <text class="amount">¥{{item.discount}}</text>
                        <text class="condition">满{{item.min}}可用</text>
                    </view>
                    <!-- 右侧信息区域 -->
                    <view class="info-wrap">
                        <text class="limit-text">{{item.limitText}}</text>
                        <text class="countdown">有效期限{{item.startTime}} - {{item.endTime}}</text>
                        <button class="receive-btn" :class="{ 'disabled': !item.isAvailable }" @click="receiveCoupon(item)"
                                :disabled="!item.isAvailable">
                            {{ item.isReceived ? '已领取' : '立即领取' }}
                        </button>
                    </view>
                </view>
            </view>

            <!-- 无优惠券提示（可选） -->
            <view class="empty-tip" v-if="couponList.length === 0">
                暂无可领取优惠券~
            </view>
        </view>

        <!-- 3. 底部说明（可选） -->
        <view class="footer-tip">
            <text>领券规则：每人限领一次，数量有限，先到先得</text>
        </view>
    </view>
</template>

<script>
import { mapState } from 'vuex';
import { getAvailableCouponList, receiveCouponApi } from '@/config/api/coupon.js';

export default {
    data() {
        return {
            navList: ['全部', '即将过期'],
            activeNav: 0,
            couponList: []
        };
    },

    computed: {
        ...mapState(['userInfo'])
    },

    mounted() {
        this.loadCoupons();
    },

    methods: {
        async loadCoupons(index = this.activeNav) {
            if (index !== undefined) {
                this.activeNav = index; // 更新当前激活的导航索引
            }
            const userId = this.userInfo.id;
            let status = index;
            if (index === 1) { // 即将过期
                status = 0;
            }
            try {
                const res = await getAvailableCouponList({
                    userId,
                    status
                });
                if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code === 200) {
                    this.couponList = res.data.data.map(item => {
                        return {
                            ...item,
                            isAvailable: true,
                            isReceived: false
                        };
                    });
                    console.log(this.couponList);
                } else {
                    console.error('请求失败:', res?.data?.msg || '未知错误');
                }
            } catch (error) {
                console.error('接口异常:', error);
                this.couponList = []; // 清空列表
                this.$message.error('数据加载失败');
            }
        },

        // 领取优惠券
        async receiveCoupon(item) {
		  if (!item.isAvailable || item.isReceived) return;
		  
		  try {
			const res = await receiveCouponApi({
			  userId: this.userInfo.id,
			  couponId: item.id
			});
			
			if (res.data.code === 200) {
			  // 更新领取状态
			  this.couponList = this.couponList.map(c => 
				c.id === item.id ? {...c, isReceived: true} : c
			  );
			  
			  uni.showToast({ title: '领取成功', icon: 'success' });
			  
			  await new Promise(resolve => setTimeout(resolve, 1000));
			  // 刷新优惠券列表
			  await this.loadCoupons();

			  // 返回到优惠券页面
			  uni.navigateBack();
			} else {
			  uni.showToast({ title: res.data.msg || '领取失败', icon: 'none' });
			}
		  } catch (error) {
			uni.showToast({ title: '请求失败', icon: 'none' });
		  }
		}
		
		
    }
};
</script>

<style scoped>
/* 页面容器 */
.lin-coupon-page {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    background-color: #f5f5f5;
}

/* 自定义导航栏 */
.custom-nav {
    background-color: #fff;
    display: flex;
    justify-content: space-around;
    padding: 16px;
}

.nav-item {
    font-size: 16px;
    color: #000;
    cursor: pointer;
}

.nav-item.active {
    border-bottom: 2px solid #fff;
}

/* 优惠券列表 */
.coupon-list {
    padding: 16px;
    flex: 1;
    /* 占满剩余空间，让底部固定 */
}

/* 单个优惠券卡片 */
.coupon-card {
    position: relative;
    /* 角标绝对定位用 */
    display: flex;
    align-items: flex-start;
    background: #fff;
    border-radius: 8px;
    padding: 12px 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    margin-bottom: 16px;
}

/* 快过期角标 */
.expired-tag {
    position: absolute;
    top: 8px;
    left: 0;
    padding: 4px 8px;
    background: #ff4d4f;
    color: #fff;
    font-size: 12px;
    border-radius: 0 4px 4px 0;
    z-index: 1;
}

/* 内容容器：左右布局 */
.coupon-content {
    display: flex;
    align-items: center;
    width: 100%;
}

/* 左侧金额区域 */
.amount-wrap {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-right: 16px;
}

.amount {
    font-size: 30px;
    font-weight: bold;
    color: #ff4d4f;
    line-height: 1.2;
}

.condition {
    font-size: 14px;
    color: #ff4d4f;
    margin-top: 4px;
}

/* 右侧信息区域 */
.info-wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    flex: 1;
}

.limit-text {
    font-size: 16px;
    color: #333;
    padding-top: 20px;
    line-height: 1.4;
}

.countdown {
    font-size: 12px;
    color: #ff4d4f;
}

/* 立即领取按钮 */
.receive-btn {
    align-self: flex-start;
    background-color: #ff4d4f;
    color: #fff;
    font-size: 14px;
    margin-right: 5px;
    border-radius: 4px;
    border: none;
    min-width: 80px;
    height: 30px;
    line-height: 30px;
    text-align: center;
}

/* 添加禁用状态样式 */
.receive-btn.disabled {
    background-color: #ccc !important;
    cursor: not-allowed;
}

.receive-btn:active {
    opacity: 0.8;
}

/* 无优惠券提示 */
.empty-tip {
    text-align: center;
    color: #999;
    font-size: 14px;
    margin-top: 40px;
}

/* 底部说明 */
.footer-tip {
    padding: 12px 16px;
    background-color: #fff;
    border-top: 1px solid #eee;
}

.footer-tip text {
    font-size: 12px;
    color: #999;
}
</style>